// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-var-requires
const express = require('express');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const webpack = require('webpack');

const { createProxyMiddleware } = require('http-proxy-middleware');

// eslint-disable-next-line @typescript-eslint/no-var-requires
const webpackDevMiddleware = require('webpack-dev-middleware');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const webpackHotMiddleware = require('webpack-hot-middleware');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const WebpackConfig = require('./webpack.dev.config');
const path = require("path");

const port = process.env.PORT || 8009;

const OpenBrowserPlugin = require('open-browser-webpack-plugin');
WebpackConfig.plugins.push(new OpenBrowserPlugin({ url: `http://localhost:${port}` }));

const app = express();

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.get('Origin') || '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
  res.header('Access-Control-Expose-Headers', 'Content-Length');
  res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
  if (req.method === 'OPTIONS') {
    return res.send(200);
  } else {
    return next();
  }
});

const compiler = webpack(WebpackConfig);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: '/__build__/',
    stats: {
      colors: true,
      chunks: false,
    },
  })
);

app.use(webpackHotMiddleware(compiler));

app.use(express.static(path.join(__dirname, '../public'), {
  /*setHeaders(res, path, stats) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
    res.header('Access-Control-Expose-Headers', 'Content-Length');
    res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
  }*/
}));


module.exports = app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`);
});
